<template>
  <a-card>
    <a-form layout="horizontal" :form="searchForm" @submit="handleSearch" autocomplete="off">
      <a-row type="flex" justify="start" :gutter="15">
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-auto-complete :data-source="suppliers" v-decorator="['supplier']" :placeholder="$t('supplier')" :filter-option="filterOption" :allowClear="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="14" :sm="24">
          <a-form-item>
            <a-space>
              <a-button htmlType="submit" type="primary" icon="search">{{ $t('search') }}</a-button>
              <a-button type="primary" icon="plus" @click="showForm(null)">{{ $t('add') }}{{ $t('commission') }}
              </a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <a-table size="small" :columns="columns" :data-source="data" :pagination="{ showSizeChanger: true, showQuickJumper: true, size:'middle', showTotal:(total, range) => `${range[0]}-${range[1]} / ${total}`, current: pageIndex, pageSize: pageSize, total: total, pageSizeOptions:['10','20','30','50','100','1000','2000'], }" :row-key="record => record.id" :loading="loading" @change="handleTableChange">
      <div slot="action" slot-scope="text, record">
        <a-space>
          <a-button @click="showForm(record)">
            <a-icon type="edit"/>
            {{ $t("edit") }}
          </a-button>
          <a-popconfirm :title='$t("are_you_sure")' ok-text="Yes" okType="danger" cancel-text="No" @confirm="deleteComm(record)">
            <a-icon slot="icon" type="question-circle-o" style="color: red"/>
            <a-button>
              <a-icon type="delete"/>
              {{ $t("delete") }}
            </a-button>
          </a-popconfirm>
        </a-space>
      </div>
      <div slot="startDate" slot-scope="text, record">
        {{ getDateRange(record.startDate, record.endDate) }}
      </div>
      <div slot="minPrice" slot-scope="text, record">
        {{ record.minPrice }} ~ {{ record.maxPrice }}
      </div>
      <div slot="startTime" slot-scope="text, record">
        {{ record.startTime }} ~ {{ record.endTime }}
      </div>
      <div slot="plusRate" slot-scope="text, record">
        {{ record.plusRateType==1?'$':'' }}{{ record.plusRate }}{{ record.plusRateType==0?'%':'' }}
      </div>
      <div slot="lossRate" slot-scope="text, record">
        {{ record.plusRateType==1?'$':'' }}{{ record.lossRate }}{{ record.plusRateType==0?'%':'' }}
      </div>
      <template v-for="(item, index) in columns" :slot="item.slotName">
        <span :key="index">{{ $t(item.slotName) }}</span>
      </template>
    </a-table>

    <a-modal v-model="editVisible" :maskClosable="false" :title="editTitle" :confirm-loading="confirmLoading"
             :okText="$t('submit')" @ok="saveForm()" @cancel="closeForm()" width="60%">
      <a-form-model ref="updateForm" layout="vertical" :model="updateForm" autocomplete="off" :rules="updateFormRules">
        <a-row :gutter="[16,0]" justify="center">
          <a-col :span="24">
            <a-form-model-item prop="supplier" :label="$t('supplier')">
              <a-select :options="supplierSels" v-model="updateForm.supplier" :placeholder="$t('supplier')" :disabled="editReadonly">
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item prop="dateRange" :label="$t('checkin') + ' (' + $t('not_fill_book_today') + ')'">
              <a-range-picker v-model="updateForm.dateRange" @change="dateChange"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item prop="time" :label="$t('time_range')">
              <a-input-group compact>
                <a-select v-model="updateForm.startTime" :options="hours" :placeholder="$t('start_time')"
                          style="width:50%" :allowClear="true">
                </a-select>
                <a-select v-model="updateForm.endTime" :options="hours" :placeholder="$t('end_time')"
                          style="width:50%" :allowClear="true">
                </a-select>
              </a-input-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item prop="priceRange" :label="$t('price_range')">
              <a-input-group compact>
                <a-input-number :min="1" v-model="updateForm.minPrice" :placeholder="$t('min')" style="width: 50%"/>
                <a-input-number :min="updateForm.minPrice" v-model="updateForm.maxPrice" :placeholder="$t('max')" style="width: 50%"/>
              </a-input-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item prop="plusRateType" :label="$t('plus_rate_type')">
              <a-radio-group v-model="updateForm.plusRateType" :default-value="0" button-style="solid">
                <a-radio-button :value="0">
                  {{ $t('plus_rate_type_0') }}
                </a-radio-button>
                <a-radio-button :value="1">
                  {{ $t('plus_rate_type_1') }}
                </a-radio-button>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item prop="plusRate" :label="$t('commission')">
              <a-input v-model="updateForm.plusRate" :addon-before="updateForm.plusRateType==1?'$':''" :addon-after="updateForm.plusRateType==0?'%':''"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item prop="lossRate" :label="$t('loss_rate')">
              <a-input v-model="updateForm.lossRate" :addon-before="updateForm.plusRateType==1?'$':''" :addon-after="updateForm.plusRateType==0?'%':''"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>

  </a-card>
</template>

<script>
import {isEmpty} from "@/utils/util";
import {getPublicData} from '@/services/public'
import {getCommissionList,updateCommission,deleteCommission} from '@/services/commission'

export default {
  name: "HotelCommission",
  props: ['Distributor','HotelId'],
  i18n: require('../i18n'),
  data() {
    return {
      suppliers: [],
      supplierSels: [],
      distributors: [],
      distributorSels: [],
      hours: [{value: 0, label: '00'},
        {value: 1, label: '01'},
        {value: 2, label: '02'},
        {value: 3, label: '03'},
        {value: 4, label: '04'},
        {value: 5, label: '05'},
        {value: 6, label: '06'},
        {value: 7, label: '07'},
        {value: 8, label: '08'},
        {value: 9, label: '09'},
        {value: 10, label: '10'},
        {value: 11, label: '11'},
        {value: 12, label: '12'},
        {value: 13, label: '13'},
        {value: 14, label: '14'},
        {value: 15, label: '15'},
        {value: 16, label: '16'},
        {value: 17, label: '17'},
        {value: 18, label: '18'},
        {value: 19, label: '19'},
        {value: 20, label: '20'},
        {value: 21, label: '21'},
        {value: 22, label: '22'},
        {value: 23, label: '23'},
      ],
      searchParams: {},
      searchForm: this.$form.createForm(this, {name: 'search'}),
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      data: [],
      columns: [
        {
          title: 'ID',
          dataIndex: 'id',
          align: 'center',
        },
        {
          dataIndex: 'supplier',
          align: 'center',
          slotName: "supplier",
          slots: { title: 'supplier' },
        },
        {
          dataIndex: 'startDate',
          align: 'center',
          slotName: "checkin",
          slots: { title: 'checkin' },
          scopedSlots: { customRender: 'startDate' },
        },
        {
          dataIndex: 'minPrice',
          align: 'center',
          slotName: "price_range",
          slots: { title: 'price_range' },
          scopedSlots: { customRender: 'minPrice' },
        },
        {
          dataIndex: 'startTime',
          align: 'center',
          slotName: "time_range",
          slots: { title: 'time_range' },
          scopedSlots: { customRender: 'startTime' },
        },
        {
          dataIndex: 'plusRate',
          align: 'center',
          slotName: "commission",
          slots: { title: 'commission' },
          scopedSlots: { customRender: 'plusRate' },
        },
        {
          dataIndex: 'lossRate',
          align: 'center',
          slotName: "loss_rate",
          slots: { title: 'loss_rate' },
          scopedSlots: { customRender: 'lossRate' },
        },{
          dataIndex: 'updatedByName',
          align:'center',
          slotName: "updatedByName",
          slots: { title: 'updatedByName' },
        },{
          dataIndex: 'updatedTime',
          align:'center',
          slotName: "updatedTime",
          slots: { title: 'updatedTime' },
        },{
          align:'center',
          scopedSlots: { customRender: 'action' },
          slotName: "operation",
          slots: { title: 'operation' },
        }
      ],
      updateForm: {
        distributor: this.$route.params.distributor,
        hotelId: this.$route.params.hotelId,
        plusRateType: 0,
        lossRate: 0,
        dateRange: []
      },
      editVisible: false,
      editReadonly: false,
      editTitle: '',
      confirmLoading: false,
      updateFormRules: {
        supplier: [{required: true, trigger: 'blur',message:' '}],
        distributor: [{required: true, trigger: 'blur',message:' '}],
        plusRate: [{required: true, trigger: 'blur',message:' '}],
      },
    }
  },
  methods: {
    dateChange(date, dateArr) {
      this.updateForm.startDate = dateArr[0]
      this.updateForm.endDate = dateArr[1]
    },
    getData() {
      getPublicData('sup_dis').then(res => {
        const {suppliers, distributors} = res.data
        this.suppliers = suppliers
        suppliers.forEach(item => {
          this.supplierSels.push({label: item, value: item})
        })
        this.distributors = distributors
        distributors.forEach(item => {
          this.distributorSels.push({label: item, value: item})
        })
      }).catch(error => {
        console.log(error)
      })
    },
    fetchData() {
      this.loading = true
      this.searchParams.distributor = this.$route.params.distributor
      this.searchParams.hotelId = this.$route.params.hotelId
      getCommissionList(this.pageIndex, this.pageSize, this.searchParams).then(res => {
        const {rows, total} = res.data.data
        this.data = rows
        this.total = total
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
      })
    },
    handleSearch(e) {
      e.preventDefault();
      this.searchForm.validateFields((error, values) => {
        this.searchParams = values;
      });
      this.pageIndex = 1
      this.fetchData()
    },
    handleTableChange(pagination) {
      if (this.pageIndex === pagination.current && this.pageSize === pagination.pageSize)
        return

      this.pageIndex = pagination.current;
      this.pageSize = pagination.pageSize;
      this.fetchData()
    },
    showForm(record) {
      if (record === null) {
        this.editTitle = this.$t('add') + this.$t('commission')
        this.editReadonly = false
      } else {
        this.editTitle = this.$t('edit') + this.$t('commission')
        record.dateRange = [record.startDate, record.endDate]
        this.updateForm = JSON.parse(JSON.stringify(record))
        this.editReadonly = true
      }
      this.editVisible = true
    },
    saveForm() {
      this.$refs.updateForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          updateCommission(this.updateForm).then(res => {
            if(res.data.success) {
              this.$message.success({content: this.$t('submitSuccess')})
              this.closeForm()
              this.fetchData()
            }else{
              this.$message.error({content: this.$t(res.data.message)})
            }
          }).catch(error => {
            console.log(error)
          })
        } else {
          return false;
        }
      });
    },
    closeForm() {
      this.confirmLoading = false
      this.editVisible = false
      this.updateForm = {
        distributor: this.$route.params.distributor,
        hotelId: this.$route.params.hotelId,
        plusRateType: 0,
        lossRate: 0,
        dateRange: []
      }
      this.$refs.updateForm.clearValidate()
    },
    deleteComm(comm) {
      deleteCommission(comm.id).then(res => {
        if(res.data.success) {
          this.$message.success({content: this.$t('deleteSuccess')})
          this.fetchData()
        }else{
          this.$message.error({content: this.$t(res.data.message)})
        }
      }).catch(error => {
        console.log(error)
      })
    },
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
      );
    },
    getDateRange(startDate, endDate){
      if(isEmpty(startDate))
        return this.$t('book_today')
      else
        return startDate + ' ~ ' + endDate
    },
  },
  created() {
    this.getData();
    this.fetchData();
  },
}
</script>

<style scoped>

</style>